#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/17
# @Author :songtx
# @File   :io_status.py

import can
import time
import numpy as np
# from write_mariaDB import write_sql


def io_status():
    global var1, var2, data_do, data_di     # 类型为list
    global l_s_time                         # 长按和短按判断，元素为True/False

    inquiry_do = can.Message(arbitration_id=0x0201, data=[0x01], is_extended_id=False)  # 问询
    bus.send(inquiry_do)                    # 0x0201 DO状态 返回513
    message_do = bus.recv(timeout=1)        # 接收数据
    type_id_do = message_do.arbitration_id  # 返回can报文类型
    if type_id_do == 513:
        # time_float1 = message_do.timestamp          # 浮点数时间戳
        # time_date1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_do.timestamp)))  # 转str时间
        # 取回4个字节,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位
        data_do = '{:0>32b}'.format(int(bin(int.from_bytes(message_do.data[0:4], "little")).replace('0b', ''), 2))
        print(data_do, type(data_do))
        if var1 != data_do:                 # 差异检测，差异写入数据库
            # write_sql(time_date1, type_id_do, data_do)
            var1 = data_do                  # 给中间值赋新值
        else:
            time.sleep(0.25)                # 无差异，0.5s扫描一次DI状态

    inquiry_di = can.Message(arbitration_id=0x0301, data=[0x01], is_extended_id=False)
    bus.send(inquiry_di)                    # 0x0301  返回769/0x0301 di状态
    message_di = bus.recv(timeout=1)        # 接收数据
    type_id_di = message_di.arbitration_id  # 返回can报文类型
    if type_id_di == 769:
        # time_float2 = message_di.timestamp          # 浮点数时间戳
        # time_date2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_di.timestamp)))  # 转str时间

        # data3 = message_di.data[0:4]  # 取回4个字,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位->反向排列
        data_di = '{:0>32b}'.format(int(bin(int.from_bytes(message_di.data[0:4], "little")).replace('0b', ''), 2))[::-1]
        print(data_di, type(data_di))
        if data_di != var2:                 # 差异检测，差异写入数据库
            # write_sql(time_date2, type_id_di, data_di)
            if var2 != 0:
                for j in range(32):         # 32点上升沿检测
                    if var2[j] == '0' and data_di[j] == '1':  # 检测上升沿
                        edge[0, j] = 1                        # 写入边缘检测edge[0]
                        time_diff[0, j] = time.time()         # 把时间写入array[0]
                for j in range(32):
                    if var2[j] == '1' and data_di[j] == '0':  # 检测下降沿
                        edge[1, j] = 1                        # 写入边缘检测edge[1]
                        time_diff[1, j] = time.time()         # 把时间写入array[1]
            var2 = data_di                                    # 给中间值赋新值
        else:
            time.sleep(0.25)  # 无差异，0.5s扫描一次DI状态
        l_s_time[0] = 0 < (time_diff[1] - time_diff[0]) < 2
        l_s_time[1] = 5 < (time_diff[1] - time_diff[0]) < 10
        print(l_s_time)


var1 = var2 = 00000000000000000000000000000000    # 参与差异判断和上升下降沿的中间变量
data_do = data_di = 0                             # 传回的DI/DO状态。
edge = np.zeros(64, np.int8).reshape(2, 32)       # DI上升/下降沿检测,edge[0,0]第1个up，edge[1,0]第1个down
time_diff = np.zeros(64, np.int8).reshape(2, 32)  # DI上升/下降沿的触发时间
l_s_time = np.zeros(64, np.int8).reshape(2, 32)   # 短按判断l_s_time[0]|长按判断l_s_time[1]
bus = can.Bus(interface='socketcan', channel='can1', receive_own_messages=eval('False'))
for i in range(5):
    io_status()
    print('+')
    print(edge)
    time.sleep()
    